const { default: Esc20140526, SendSmsRequest, QuerySendDetailsRequest } = require('@alicloud/dysmsapi20170525');
const { Config } = require('@alicloud/openapi-client');
const { RuntimeOptions } = require('@alicloud/tea-util');
const account = require('@/config/Account')
const { generateCode } = require('./gencode')
const result = require('@/config/handle')
const moment = require('moment')
moment.locale('zh-cn')

// 阿里云短信验证码
let config = new Config({
    accessKeyId: account.ALI_KEYID,
    accessKeySecret: account.ALI_KEYSECRET,
})
const client = new Esc20140526(config)
const runtime = new RuntimeOptions({})

// 发送验证码
const verCode = async function (phoneNumbers) {
    let sendSmsRequest = new SendSmsRequest({
        phoneNumbers: phoneNumbers,
        signName: account.ALI_SIGNNAME,
        templateCode: account.ALI_CODE,
        templateParam: `{"code":${generateCode()}}`,
    });
    try {
        const res = await client.sendSmsWithOptions(sendSmsRequest, runtime);
        return res
    } catch (error) {
        throw new result('发送验证码失败', 500, error)
    }
}

// 验证验证码是否正确
const queryCode = async function (phoneNumber, bizId, code) {
    const sendDate = moment().format('YYYYMMDD')
    let querySendDetailsRequest = new QuerySendDetailsRequest({
        phoneNumber,
        sendDate,
        pageSize: 10,
        currentPage: 1,
        bizId,
    });
    try {
        const res = await client.querySendDetailsWithOptions(querySendDetailsRequest, runtime);
        if (res.body.code === 'OK') {
            if (res.body.smsSendDetailDTOs.smsSendDetailDTO.length === 0) {
                throw { message: '手机号没有发送过验证码', code: 422 }
            } else {
                const str = res.body.smsSendDetailDTOs.smsSendDetailDTO[0].content
                const nums = str.match(/\d+/g).map(Number)
                if (code == nums[0]) {
                    return 'SUCCESS'
                } else {
                    throw { message: '验证码不正确', code: 422 }
                }
            }
        } else {
            throw { message: res.body.message, code: 422 }
        }
    } catch (error) {
        throw new result(
            error.message ? error.message : '发生未知错误',
            error.code ? error.code : 500,
            error.message ? null : error,
        )
    }
}

module.exports = {
    verCode,
    queryCode
}